<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Victor
 * Date: 08.12.11
 * Time: 2:01
 * To change this template use File | Settings | File Templates.
 */

class practiceController extends Core_BaseController
{

    function goAction($idLesson = 1)
    {

        $permission = array('guest', 'admin', 'moderator');
        $this->twig = $this->getRegistry()->twig;

        $allow = $this->userHasPermission($permission);
        $auth = $this->checkAuth();
        $role = $this->getAuth()->getUserRoles($auth);


        if ($allow) {
            $questionManager = new Question_Question();
            $lessonManager = new Lesson_Lesson();
            $answerManager = new Answer_Answer();

            $questions = $questionManager->getAllQuestionToLesson($idLesson);
            foreach ($questions as $key => $value) {
                $idquestion = $key;

                $answers[$idquestion] = $answerManager->getAllAnswerToQuestion($idquestion);
            }

            //output
            $data = array();
            $data = array_merge($data, array('questions' => $questions));
            $data = array_merge($data, array('answers' => $answers));
            $data = array_merge($data, array('role' => $role));
            $data = array_merge($data, $auth);

            $template = $this->twig->loadTemplate('base.html.twig');
            $template->display($data);


        } else
        {
            $template = $this->twig->loadTemplate('access.html.twig');
            echo $template->render(array());
        }
    }

    function indexAction()
    {

    }

    function resultsAction($idLesson = -1)
    {
        //enable access for `guest` because debug mode.
        $permission = array('guest','admin', 'moderator');
        $this->twig = $this->getRegistry()->twig;

        $allow = $this->userHasPermission($permission);
        $auth = $this->checkAuth();
        $role = $this->getAuth()->getUserRoles($auth);
        $messages = array();
        $lessonManager = new Lesson_Lesson();
        $questionManager = new Question_Question();
        $userManager = new User_Manager();
        $answerManager = new Answer_Answer();
        $id = $this->getAuth()->getUserIdByLogin($auth['name']);
        $userProfile = $userManager->getUserIdProfileById($id);


        if ($allow) {
            if (empty($_POST))
            $messages[] = 'Ви не відповіли на всі питання !';

            $isCompleted = $lessonManager->isCompleted($idLesson, $userProfile);
            //$this->vardump("Is completed",$isCompleted);
            if($isCompleted)
              $messages[] = 'Ви Проходили тест !';
            else $messages=array();
           // $this->vardump('counr messages',count($messages));
            //$this->vardump('messages',$messages);

            if(count($messages) == 0 && $isCompleted == false){
                $idquestionAnswer = array();
                       foreach($_POST as $key=>$value){
                           $idquestionAnswer = explode('_',$key);
                           $idquestion  =  $idquestionAnswer[0];
                           $answer = $idquestionAnswer[1];
                           $correctAnswers = $questionManager->getCorrectValueFromQuestion($idquestion);
                           $corrects[$idquestion] = $correctAnswers;
                           $answers[$idquestion] = $answer;
                       }
                    // $this->vardump("idquestionAnswer",$idquestionAnswer);
                      $lessonManager->addCompletedLesson($idLesson,$userProfile);
                $mark = $answerManager->calculateMark($answers,$corrects);
                   //$this->vardump("MARK is",$mark);
                      $lessonManager->setLessonMark($idLesson,$userProfile,$mark);
                 $mark = $lessonManager->getLessonMark($idLesson,$userProfile);


                 $template = $this->twig->loadTemplate('practice_result.html.twig');
                $template->display(array('mark' => $mark));

            }else{
                //show marks
                $mark = 0;
                $isCompleted = $lessonManager->isCompleted($idLesson, $userProfile);
                if($isCompleted)

                $mark = $lessonManager->getLessonMark($idLesson,$userProfile);

                $data = array('messages' =>$messages,
                                   'role' => $role,
                                   'mark' =>$mark,
                'role' => $role
                );
                 $data = array_merge($data, $auth);

                $template = $this->twig->loadTemplate('practice_result.html.twig');
                $template->display($data);
            }


        }else {
                $template = $this->twig->loadTemplate('access.html.twig');
                echo $template->render(array());
            }
    }

        function questionAction($idLesson = 1)
        {

            //$this->vardump("idLEsson = ",$idLesson);
            $permission = array('admin', 'moderator');
            $this->twig = $this->getRegistry()->twig;
            $allow = $this->userHasPermission($permission);
            $auth = $this->checkAuth();
            $role = $this->getAuth()->getUserRoles($auth);
            if ($allow) {

                $questionManager = new Question_Question();
                $answerManager = new Answer_Answer();
                $lessonManager = new Lesson_Lesson();
                $userManager = new User_Manager();

                $userProfile = $userManager->getUserIdProfileById($_COOKIE['id']);
                $isCompleted = $lessonManager->isCompleted($idLesson, $userProfile);

                if ($isCompleted) {
                    header("Location:practice/results/" . $idLesson);
                }

                $questions = $questionManager->getAllQuestionToLesson($idLesson);
                foreach ($questions as $key => $value) {
                    $idquestion = $key;

                    $answers[$idquestion] = $answerManager->getAllAnswerToQuestion($idquestion);
                }

                //output
               // $this->vardump("questions",$questions);

                //$this->vardump("Answers",$answers);
                $data = array();
                $data = array_merge($data, array('questions' => $questions,
                                                'answers' => $answers,
                                                'idlesson' => $idLesson,
                                           'role' => $role));
                $data = array_merge($data, $auth);

                $template = $this->twig->loadTemplate("pra.html.twig");

                echo $template->render($data);


            } else
            {

                $template = $this->twig->loadTemplate('access.html.twig');
                echo $template->render(array());
            }

        }

        function addAction()
        {
            $permission = array('admin');
            $auth = $this->checkAuth();
            $allow = $this->userHasPermission($permission);

            $this->twig = $this->getRegistry()->twig;
            $lessonManager = new Lesson_Lesson();
            $answerManager = new Answer_Answer();
            $questionManager = new Question_Question();
            $userManager = new User_Manager();
            $messages = array();
            $data = array();
            //var_dump($allow);

            if ($allow) {
                $role = $this->getAuth()->getUserRoles($auth);
                if (empty($_POST))
                    $messages[] = 'Введіть будь-ласка дані';
                if (!is_numeric($_POST['lesson']))
                    $messages[] = 'Виберіть урок!';
                if (strlen($_POST['question']) < 3)
                    $messages[] = 'Мінімальна довжина заголовку 4 символа';
                if (strlen($_POST['question']) == 0)
                    $messages[] = 'Питання не повинен бути пустий';
                if (strlen($_POST['answers']) == 0)
                    $messages[] = 'відповіді не повинені бути пустими';
                if (!empty($_POST['answers'])) {
                    $answersFromUser = $_POST['answers'];
                    $sd = str_replace("\r\n", "\n", $answersFromUser);
                    $answers[] = explode("\n", $sd);


                    if (count($answers) == 1)
                        $answers = $answers[0];

                    $isMessage = false;
                    $hasCorrect = false;
                    foreach ($answers as $number => $answer) {
                        if (strlen($answer) <= 3 || $isMessage == true) {
                            $messages[] = 'Відповіді не повинні бути коротшими ніж 3 символа';
                            $isMessage = true;
                        }

                        if ($hasCorrect != true)
                            $hasCorrect = $answerManager->isCorrectAnswer($answer);
                    }
                    if (!$hasCorrect) $messages[] = 'Повинна бути одна правильна відповідь!';
                }


                if (count($messages) == 0) {
                    $userProfile = $userManager->getUserIdProfileById($_COOKIE['id']);
                    $lessonId = $_POST['lesson'];
                    $textQuestion = $_POST['question'];
                    $idBaseQuestion = $questionManager->addBaseQuestion($lessonId, $textQuestion, $userProfile);
                    //$this->vardump("Base Question",$idBaseQuestion);
                    //add
                    //parse text answers


                    foreach ($answers as $number => $answer) {
                        $isCorrect = false;
                        if ($answerManager->isCorrectAnswer($answer)) {
                            //remove /q/
                            $answer = $answerManager->removeSign($answer);
                            $isCorrect = true;
                        }
                        $idAnswer = $answerManager->addAnswer($answer);
                      // $this->vardump("idAnswer",$idAnswer);
                        $result = $answerManager->addAnswerToLesson($idBaseQuestion, $idAnswer, $isCorrect);
                        //  $this->vardump("result adding",$result);
                        //add

                    }

                    if (!$result) $messages[] = "Помилка виконання !";


                }

                $lessons = $lessonManager->getAllLessons();

                $data = array_merge($data, $auth);
                $data = array_merge($data, array('lessons' => $lessons));
                $data = array_merge($data, array('role' => $role,
                                                'messages' => $messages));

                $template = $this->twig->loadTemplate('practice_add.html.twig');
                $template->display($data);
            } else {

                $template = $this->twig->loadTemplate('access.html.twig');
                echo $template->render(array());
            }


        }
    }

        ?>
